import { useState, memo, forwardRef, useRef, useEffect, lazy, Suspense, useMemo } from 'react'
import { Button, Form, Input, Select, Checkbox, Row, Col, Radio, InputNumber, message } from 'antd'
import { uid } from 'uid'
import { useSelector } from 'react-redux'
import bus from '../../../../../utils/eventBus';
import { SET_APP_TYPE, files, proTypeList, codePosition, codeTypeList, SET_ICON_LIST, SET_CODE_LIST } from "../config";
import LdDrawer from '../../../../../components/LdDrawer'
import previewCode from '../../../../../assets/system/preview-code.png'
import code from '../../../../../assets/system/code@2x.png'
import './index.scss'
const TransferDialog = lazy(() => import('../Transfer'))
const BarCodeView = forwardRef((props: any, ref: any) => {
    const { enableClone = true, enablePrint = true } = useSelector((state: any) => state.licenseInfoReducer.licenseInfo)
    const formRef = useRef<any>(null)
    const { onClose, refresh, detailRow } = props
    const title = detailRow.isRelease === 1 ? '查看' : detailRow.id ? '设置' : '新增'
    const [loading, setLoading] = useState<boolean>(false)
    const [position, setPosition] = useState<any>({})
    const [isShowSn, setIsShowSn] = useState<boolean>(false)
    const [openTransfer, setOpenTransfer] = useState<boolean>(false)
    const [viewCode, setViewCode] = useState<string>('')
    const barSnRules = useRef<any>({})
    const barImageRules = useRef<any>({})
    const transferParams = useRef<any>(undefined)

    const appTypeList = useMemo(() => {
        return !enableClone && !enablePrint ?
            [] : !enableClone ?
                [...SET_APP_TYPE].filter(item => item.value !== 4) : [...SET_APP_TYPE].filter(item => item.value !== 1)
    }, [enableClone, enablePrint])
    const handleSave = () => {
        formRef.current.validateFields().then((res: any) => {
            const { imageRuleName, isShowSn, key, name, snRuleName, version, enable, files } = res
            const id = detailRow.id || uid(32)
            const params = {
                id,
                imageRuleName,
                isShowSn,
                key,
                name,
                snRuleName,
                version,
                enable,
                docType: files.join(","),
                strategyRules: [
                    { name: 'barstategy.rule.generator.pos', value: res['barstategy.rule.generator.pos'] },
                    { name: 'barstategy.rule.generator.type', value: res['barstategy.rule.generator.type'] },
                    { name: 'barstategy.rule.offsetX', value: `${res['barstategy.rule.offsetX']}` },
                    { name: 'barstategy.rule.offsetY', value: `${res['barstategy.rule.offsetY']}` }
                ],
                snRules: [
                    { name: 'barSn.rule.align', value: res['barSn.rule.align'] },
                    { name: 'barSn.rule.fontSize', value: `${res['barSn.rule.fontSize']}` },
                    { name: 'barSn.rule.space', value: `${res['barSn.rule.space']}` },
                    { name: "barSn.rule.prefix", value: barSnRules.current?.['barSn.rule.prefix'] },
                    { name: "barSn.rule.split", value: barSnRules.current?.['barSn.rule.split'] }
                ],
                imageRules: [
                    { name: 'barImage.rule.type', value: res['barImage.rule.type'] },
                    { name: 'barImage.rule.width', value: `${res['barImage.rule.width']}` },
                    { name: 'barImage.rule.prefix', value: barImageRules.current?.['barImage.rule.prefix'] },
                    { name: 'barImage.rule.text.split', value: barImageRules.current?.['barImage.rule.text.split'] }
                ]
            }
            setLoading(true)
            window.chromePro.updateBceCodeStrategy(JSON.stringify(params));
        }).catch((err: any) => {

        })
    }
    const handleSet = (keyWord: string) => {
        //解析数据
        const handleData = (data: string, rightDefaultData: Array<string>) => {
            const splitCodeArray = ["-", "、", "/", "."]; //分割符，后续多个可以在这边添加
            const splitCode = splitCodeArray.filter((item) =>
                new Set(data.split("")).has(item)
            );
            let rightData = [];
            if (!data.includes(splitCode[0])) {
                rightData = data ? [data] : rightDefaultData;
            } else {
                rightData = data.split(`${splitCode[0]}`);
            }
            return {
                rightData,
            };
        };
        const { imageRuleName = '', snRuleName = '' } = formRef.current.getFieldsValue()
        if (keyWord === "code-content") {
            const params = handleData(imageRuleName, [
                "二维码版本",
                "条码序号",
            ]);
            transferParams.current = {
                data: [...SET_ICON_LIST],
                title: "条码图标规则设置",
                keyWord,
                params: {
                    ...params,
                    split: barImageRules.current?.['barImage.rule.text.split'],
                    prefix: barImageRules.current?.['barImage.rule.prefix'],
                },
            };
        } else {
            const params = handleData(snRuleName, ["流水号"]);
            transferParams.current = {
                data: [...SET_CODE_LIST],
                title: "条码编号规则设置",
                keyWord,
                params: {
                    ...params,
                    split: barSnRules.current?.['barSn.rule.split'],
                    prefix: barSnRules.current?.['barSn.rule.prefix'],
                },
            };
        }
        setOpenTransfer(true)
    }
    const formValueChange = (currentValue: any, allValue: any) => {
        const { isShowSn } = currentValue
        if (currentValue['barstategy.rule.generator.pos']) {
            handlePosition(currentValue['barstategy.rule.generator.pos'])
        }
        if (isShowSn !== undefined) {
            const { snRuleName = '' } = allValue
            setIsShowSn(isShowSn ? true : false)
            setViewCode(snRuleName.includes("前缀") ? snRuleName.replace("前缀", barSnRules.current?.['barSn.rule.prefix']) : snRuleName)
        }
    }
    const handlePosition = (position: string) => {
        let codePosition = undefined
        switch (position) {
            case "1" || 1:
                codePosition = { left: '15px', top: '5px' }
                break
            case "32" || 32:
                codePosition = { left: '60px', top: '5px' }
                break
            case "4" || 4:
                codePosition = { right: '15px', top: '5px' }
                break
            case "2" || 2:
                codePosition = { left: '15px', bottom: '15px' }
                break
            case "16" || 16:
                codePosition = { left: '60px', bottom: '15px' }
                break
            case "8" || 8:
                codePosition = { right: '15px', bottom: '15px' }
                break
            default:
                codePosition = { display: 'none' }
        }
        setPosition(codePosition)
    }
    const updateBceCodeStrategyFinished = (res: any) => {
        setLoading(false)
        if (res.code === 200) {
            message.success('操作成功')
            onClose && onClose()
            refresh && refresh()
        } else {
            message.error(res.msg)
        }
    }
    const getBceCodeStrategyVersionFinished = (res: any) => {
        if (res.code === 200) {
            formRef.current.setFieldsValue({
                version: res.data,
                isShowSn: 1,
                enable: 1,
                ['barstategy.rule.generator.pos']: '1'
            })
            handlePosition('1')
        } else {
            message.error('系统异常')
        }
    }
    const handleViewData = async () => {
        await 1
        const { strategyRules, snRules, imageRules, name, version, key, enable, docType, isShowSn, imageRuleName, snRuleName } = detailRow
        const barState: any = {}
        const barSn: any = {}
        const barImage: any = {}
        strategyRules.map((item: any) => {
            barState[item.name] = item.value
        })
        snRules.map((item: any) => {
            barSn[item.name] = item.value
        })
        imageRules.map((item: any) => {
            barImage[item.name] = item.value
        })
        handlePosition(barState['barstategy.rule.generator.pos'])
        formRef.current?.setFieldsValue({
            name,
            version,
            key,
            enable,
            files: docType.split(','),
            isShowSn,
            imageRuleName,
            snRuleName,
            ...barState,
            ...barSn,
            ...barImage
        })
        barSnRules.current = { ...barSn }
        barImageRules.current = { ...barImage }
        setIsShowSn(isShowSn ? true : false)
        setViewCode(snRuleName.includes("前缀") ? snRuleName.replace("前缀", barImage['barImage.rule.prefix']) : snRuleName)
    }
    const closeTransfer = () => {
        setOpenTransfer(false)
    }
    const insertContent = (data: any) => {
        const { content, split, prefix } = data;
        const { keyWord } = transferParams.current
        //图形编码
        if (keyWord === "code-code") {
            formRef.current.setFieldsValue({
                'snRuleName': content
            })
            barSnRules.current = {
                ...barSnRules.current,
                ['barSn.rule.prefix']: prefix,
                ['barSn.rule.split']: split
            }
            const { isShowSn, snRuleName } = formRef.current.getFieldsValue()
            setIsShowSn(isShowSn ? true : false)
            setViewCode(snRuleName.includes("前缀") ? snRuleName.replace("前缀", prefix) : snRuleName)
            //图形图标
        } else {
            formRef.current.setFieldsValue({
                'imageRuleName': content
            })
            barImageRules.current = {
                ...barImageRules.current,
                ["barImage.rule.prefix"]: prefix,
                ['barImage.rule.text.split']: split
            }
        }
    }
    useEffect(() => {
        if (detailRow.id) {
            handleViewData()
        } else {
            window.chromePro.getBceCodeStrategyVersion(JSON.stringify({}))
        }
        bus.addListener('updateBceCodeStrategyFinished', updateBceCodeStrategyFinished)
        bus.addListener('getBceCodeStrategyVersionFinished', getBceCodeStrategyVersionFinished)
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener('updateBceCodeStrategyFinished', updateBceCodeStrategyFinished)
            bus.removeListener('getBceCodeStrategyVersionFinished', getBceCodeStrategyVersionFinished)
        }
    }, [])
    return (
        <>
            <LdDrawer
                onClose={onClose}
                title={title + '条码策略'}
            >
                {
                    detailRow.isRelease === 0 ?
                        <div slot="actionBtn">
                            <Button type="primary" loading={loading} onClick={handleSave}>保 存</Button>
                        </div>
                        : null
                }
                <div className="h100 barCodeView">
                    <div className="content-basic">
                        <div className="title">
                            <span></span>
                            <span>基本信息</span>
                        </div>
                    </div>
                    <Form preserve={false} onValuesChange={formValueChange} labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} ref={formRef} disabled={detailRow.isRelease === 1}>
                        <Row gutter={24}>
                            <Col span={12}>
                                <Form.Item name="name" label="条码策略名称" rules={[{ required: true, message: '请输入条码策略名称' }]}>
                                    <Input placeholder='请输入条码策略名称' />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="version" label="条码策略版本" rules={[{ required: true, message: '请输入条码策略版本' }]}>
                                    <Input disabled placeholder='请输入条码策略版本' />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="key" label="应用类型" rules={[{ required: true, message: '请选择应用类型' }]}>
                                    <Select placeholder="请选择应用类型" options={[...appTypeList]}></Select>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="策略是否启用" name="enable" rules={[{ required: true, message: '请选择策略是否启用' }]}>
                                    <Radio.Group>
                                        <Radio value={1}>是</Radio>
                                        <Radio value={0}>否</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="适用文件类型" name="files" rules={[{ required: true, message: '请选择适用文件类型' }]}>
                                    <Checkbox.Group options={[...files]}></Checkbox.Group>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="isShowSn" label="编码是否显示" rules={[{ required: true, message: '请选择编码是否显示' }]}>
                                    <Radio.Group>
                                        <Radio value={1}>显示</Radio>
                                        <Radio value={0}>不显示</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barstategy.rule.generator.type" label="生成方式" rules={[{ required: true, message: '请选择生成方式' }]}>
                                    <Select placeholder="请选择生成方式" options={[...proTypeList]} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barstategy.rule.generator.pos" label="条码位置" rules={[{ required: true, message: '请选择条码位置' }]}>
                                    <Select placeholder="请选择条码位置" options={[...codePosition]} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barstategy.rule.offsetX" label="X轴偏移" rules={[{ required: true, message: '请输入X轴偏移' }]}>
                                    <InputNumber style={{ width: '100%', margin: 0 }} placeholder='请输入X轴偏移' precision={0} controls={false} min={0} max={100} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barstategy.rule.offsetY" label="Y轴偏移" rules={[{ required: true, message: '请输入Y轴偏移' }]}>
                                    <InputNumber style={{ width: '100%', margin: 0 }} placeholder='请输入Y轴偏移' precision={0} controls={false} min={0} max={100} />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item label="条码图标设置" labelAlign='left'></Form.Item>
                            </Col>
                            <Col span={22}>
                                <Form.Item name="imageRuleName" label="内容规则" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} rules={[{ required: true, message: '请设置内容规则' }]}>
                                    <Input placeholder="请设置内容规则" disabled style={{}} />
                                </Form.Item>
                            </Col>
                            <Col span={2}>
                                <Button style={{ padding: 0 }} type="link" onClick={() => handleSet('code-content')}>设置</Button>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barImage.rule.type" label="编码类型" rules={[{ required: true, message: '请选择编码类型' }]}>
                                    <Select placeholder="请选择编码类型" options={[...codeTypeList]} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barImage.rule.width" label="图标宽度" rules={[{ required: true, message: '请输入图标宽度' }]}>
                                    <InputNumber style={{ width: '100%', margin: 0 }} placeholder='请输入图标宽度' precision={0} controls={false} min={0} max={100} />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="条码编号设置" labelAlign='left'></Form.Item>
                            </Col>
                            <Col span={22}>
                                <Form.Item rules={[{ required: true, message: "请设置编号规则" }]} labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="编号规则" name="snRuleName">
                                    <Input placeholder="请设置编号规则" style={{}} disabled />
                                </Form.Item>
                            </Col>
                            <Col span={2}>
                                <Button type="link" style={{ padding: 0 }} onClick={() => handleSet('code-code')}>设置</Button>
                            </Col>
                            <Col span={24}>
                                <Form.Item labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="对齐方式" name="barSn.rule.align" rules={[{ required: true, message: '请选择对齐方式' }]}>
                                    <Radio.Group>
                                        <Radio value='1'>左对齐</Radio>
                                        <Radio value='2'>居中对齐</Radio>
                                        <Radio value="4">右对齐</Radio>
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barSn.rule.fontSize" label="字体大小" rules={[{ required: true, message: "请输入字体大小" }]}>
                                    <InputNumber style={{ width: '100%', margin: 0 }} placeholder='请输入字体大小' precision={0} controls={false} max={36} />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item name="barSn.rule.space" label="字码间距" rules={[{ required: true, message: '请输入字码间距' }]}>
                                    <InputNumber style={{ width: '100%', margin: 0 }} placeholder='请输入字码间距' precision={0} controls={false} max={36} />
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="预览" labelAlign='left'></Form.Item>
                                <div className="preview-box">
                                    <div className="preview-box-bigImage">
                                        <img draggable={false} src={previewCode} alt="" />
                                        <img draggable={false} src={code} style={{ ...position }} alt="" className="preview-box-smallImage" />
                                    </div>
                                    <div className="code-box">
                                        <img draggable={false} src={code} alt="" />
                                        {
                                            isShowSn ? <span>{
                                                viewCode
                                            }</span> : null
                                        }
                                    </div>
                                </div>
                            </Col>
                        </Row>
                    </Form>
                </div>
            </LdDrawer>
            <Suspense>
                {
                    openTransfer ? <TransferDialog insert={insertContent} closeVisible={closeTransfer} transfer={transferParams.current} /> : null
                }
            </Suspense>
        </>
    )
})
export default memo(BarCodeView)